package com.alexrnl.BetaSeriesFileManager.API;

import java.util.logging.Logger;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * @author Alex
 *
 */
public class Utils {
	private static Logger	T	= Logger.getLogger(Utils.class.getName());

	/**
	 * Check if the request has been correctly executed.
	 * @param doc the document
	 * @return <code>true</code> if the query to the API has not been successful.
	 */
	public static boolean hasError (final Document doc) {
		T.fine("Checking document for errors");
		Node node = doc.getFirstChild().getFirstChild();

		while (node != null) {
			if (node.getNodeName().equals("code")) {
				T.fine("'code' node found.");
				if (!node.getTextContent().equals("1")) {
					T.info("'code' was wrong: " + node.getTextContent());
					return true;
				}
			}
			if (node.getNodeName().equals("errors")) {
				T.fine("'errors' node found.");
				Node errors = node.getFirstChild();
				while (errors != null) {
					if (errors.getNodeName().equals("error")) {
						T.info("'error' exists...");
						return true;
					}
					errors = errors.getNextSibling();
				}
			}
			node = node.getNextSibling();
		}
		T.fine("Code was OK and no error were found.");
		return false;
	}
}
